<?php

namespace MoChat\App\Client\Action\Dashboard\FollowRecord;

use Hyperf\DbConnection\Db;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Client\Constants\ClientFollowRecordTypeCode;
use MoChat\App\Client\Logic\Detail\HeadLogic;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\FollowRecord\IndexLogic;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 跟进记录-列表
 * @Controller
 */
class FollowList extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     *
     * @RequestMapping(path="/dashboard/client/followRecord/list", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $data = $this->request->all();
        $list = Db::table('client_follow_record as record')
            ->when(!empty($data['followUp']), function ($query) use ($data) {
                //类型（1：电话。2：面访。3：企业微信）
                $query->where('record.type', '=', $data['followUp']);
            })
            ->when(!empty($data['enterpriseId']), function ($query) use ($data) {
                $query->where('client.enterprise_name', 'like', '%'.$data['enterpriseId'].'%');
            })
            ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('employee.id', '=', $data['employeeId']);
            })
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('record.followed_at', [$data['startTime'], $data['endTime']]);
            })
            ->when(!empty($data['orderBy']), function ($query) use ($data) {
                $orderBy=json_decode($data['orderBy'],true);
                if (!empty($orderBy)){
                    $query->orderBy('record.followed_at', str_replace('end','',$orderBy['followedAt']));
                }
            })
            ->leftJoin('work_employee as employee', 'employee.id', 'record.user_id')//user_id记录的是员工id
//            ->leftJoin('user as user','user.id','employee.log_user_id')//user_id记录的是员工id
            ->join('client as client', 'client.id', 'record.client_id')
            ->leftJoin('work_employee as binDingEmployee', 'binDingEmployee.id', 'client.work_employee_id')
            ->select([
                'record.id',//记录id
                'client.id as clientId',
                'employee.name',//员工
                'client.enterprise_name as enterpriseName',//呼叫客户
                'client.b2b_user_type as b2bUserType',//客户等级
                Db::raw('"" as label'),//客户标签
                'binDingEmployee.name as binDingEmployeeName',//绑定员工
                'record.followed_at as followedAt',//跟进时间
                'record.type',//类型（1：电话。2：面访。3：企业微信）
                'record.remark',//跟进内容
            ])
            ->orderByDesc('record.id')
            ->paginate();
        $list || $list = collect([]);
        $list = $list->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$datum) {
                $datum->b2bUserType = ClientTypeCode::getMessage($datum->b2bUserType);
                $datum->typeString = ClientFollowRecordTypeCode::getMessage($datum->type);
                $datum->label=[];
            }
            unset($datum);
        }
        return $list;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }
}
